// Global variable to store banner element for later updates
let bannerElement = null;

function addWarningBanner(warningText, backgroundColor, textColor = '#ffffff', bannerPosition = 'top-center') {
  // Check if banner already exists to avoid duplicates
  if (document.querySelector('#prod-warning-banner')) {
    // Update existing banner if needed
    updateBannerText(warningText, backgroundColor, textColor, bannerPosition);
    return;
  }
  
  // Check if this is a KubeSphere URL and extract namespace if applicable
  const currentUrl = window.location.href;
  let displayText = warningText;
  
  // Check if URL contains /clusters/ pattern for KubeSphere
  if (currentUrl.includes('/clusters/')) {
    // Extract namespace from URL pattern: .../projects/{namespace}/...
    const namespaceMatch = currentUrl.match(/\/projects\/([^\/]+)\//);
    if (namespaceMatch && namespaceMatch[1]) {
      const namespace = namespaceMatch[1];
      displayText = `${warningText} Namespace: ${namespace}`;
    }
  }
  // Check if URL contains /terminal/ pattern for KubeSphere terminal
  else if (currentUrl.includes('/terminal/')) {
    // Extract namespace from URL pattern: .../projects/{namespace}/...
    const namespaceMatch = currentUrl.match(/\/projects\/([^\/]+)\//);
    if (namespaceMatch && namespaceMatch[1]) {
      const namespace = namespaceMatch[1];
      displayText = `${warningText} Namespace: ${namespace}`;
    }
  }
  
  const banner = document.createElement('div');
  banner.id = 'prod-warning-banner';
  // Reset all styles to avoid interference from website CSS
  banner.style.all = 'initial';
  banner.style.backgroundColor = backgroundColor;
  banner.style.color = textColor;
  banner.style.padding = '5px 10px';
  banner.style.position = 'fixed';
  banner.style.zIndex = '9999';
  banner.style.fontSize = '18px';
  banner.style.textAlign = 'center';
  banner.style.whiteSpace = 'nowrap';
  banner.style.borderRadius = '8px';
  banner.style.display = 'flex';
  banner.style.alignItems = 'center';
  banner.style.justifyContent = 'space-between';
  banner.style.fontFamily = 'Arial, sans-serif';
  banner.style.fontWeight = 'normal';
  banner.style.boxSizing = 'border-box';
  // Add top margin and shadow
  banner.style.top = '10px';
  banner.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.2)';
  
  // Apply position based on bannerPosition
  applyBannerPosition(banner, bannerPosition);
  
  // Create text span
  const textSpan = document.createElement('span');
  textSpan.textContent = displayText;
  textSpan.style.all = 'initial';
  textSpan.style.flexGrow = '1';
  textSpan.style.marginRight = '10px';
  textSpan.style.color = textColor;
  textSpan.style.fontSize = '18px';
  textSpan.style.fontFamily = 'Arial, sans-serif';
  textSpan.style.fontWeight = 'normal';
  textSpan.style.lineHeight = 'normal';
  
  // Create delete button with SVG icon
  const deleteButton = document.createElement('button');
  deleteButton.style.all = 'initial';
  deleteButton.innerHTML = `
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M18 6L6 18" stroke="${textColor}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      <path d="M6 6L18 18" stroke="${textColor}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>
  `;
  deleteButton.style.background = 'none';
  deleteButton.style.border = 'none';
  deleteButton.style.color = 'white';
  deleteButton.style.cursor = 'pointer';
  deleteButton.style.padding = '2px';
  deleteButton.style.width = '24px';
  deleteButton.style.height = '24px';
  deleteButton.style.display = 'flex';
  deleteButton.style.alignItems = 'center';
  deleteButton.style.justifyContent = 'center';
  deleteButton.style.fontFamily = 'Arial, sans-serif';
  deleteButton.title = '点击关闭横幅，刷新页面重新显示';
  
  // Add click event to delete button
  deleteButton.addEventListener('click', function() {
    banner.remove();
    bannerElement = null;
  });
  
  // Add elements to banner
  banner.appendChild(textSpan);
  banner.appendChild(deleteButton);
  
  // Store reference to banner for later updates
  bannerElement = banner;

  document.body.prepend(banner);
}

// Function to apply position styles based on bannerPosition
function applyBannerPosition(banner, bannerPosition) {
  // Reset position styles first
  banner.style.top = '';
  banner.style.bottom = '';
  banner.style.left = '';
  banner.style.right = '';
  banner.style.transform = '';
  
  switch(bannerPosition) {
    case 'top-center':
      banner.style.top = '10px';
      banner.style.left = '50%';
      banner.style.transform = 'translateX(-50%)';
      break;
    case 'bottom-center':
      banner.style.bottom = '10px';
      banner.style.left = '50%';
      banner.style.transform = 'translateX(-50%)';
      break;
    case 'top-left':
      banner.style.top = '10px';
      banner.style.left = '10px';
      banner.style.transform = 'none';
      break;
    case 'top-right':
      banner.style.top = '10px';
      banner.style.right = '10px';
      banner.style.left = 'auto';
      banner.style.transform = 'none';
      break;
    case 'bottom-left':
      banner.style.bottom = '10px';
      banner.style.left = '10px';
      banner.style.transform = 'none';
      break;
    case 'bottom-right':
      banner.style.bottom = '10px';
      banner.style.right = '10px';
      banner.style.left = 'auto';
      banner.style.transform = 'none';
      break;
    default:
      // Default to top-center if position is not recognized
      banner.style.top = '10px';
      banner.style.left = '50%';
      banner.style.transform = 'translateX(-50%)';
      break;
  }
}

// Function to update banner text when URL changes
function updateBannerText(warningText, backgroundColor, textColor = '#ffffff', bannerPosition = 'top-center') {
  if (!bannerElement) return;
  
  const currentUrl = window.location.href;
  let displayText = warningText;
  
  // Check if URL contains /clusters/ pattern for KubeSphere
  if (currentUrl.includes('/clusters/')) {
    // Extract namespace from URL pattern: .../projects/{namespace}/...
    const namespaceMatch = currentUrl.match(/\/projects\/([^\/]+)\//);
    if (namespaceMatch && namespaceMatch[1]) {
      const namespace = namespaceMatch[1];
      displayText = `${warningText} Namespace: ${namespace}`;
    }
  }
  // Check if URL contains /terminal/ pattern for KubeSphere terminal
  else if (currentUrl.includes('/terminal/')) {
    // Extract namespace from URL pattern: .../projects/{namespace}/...
    const namespaceMatch = currentUrl.match(/\/projects\/([^\/]+)\//);
    if (namespaceMatch && namespaceMatch[1]) {
      const namespace = namespaceMatch[1];
      displayText = `${warningText} Namespace: ${namespace}`;
    }
  }
  
  // Update text content
  const textSpan = bannerElement.querySelector('span');
  if (textSpan) {
    textSpan.textContent = displayText;
  }
  
  // Update styles
  bannerElement.style.backgroundColor = backgroundColor;
  bannerElement.style.color = textColor;
  
  // Update position
  applyBannerPosition(bannerElement, bannerPosition);
  
  // Update text span color
  if (textSpan) {
    textSpan.style.color = textColor;
  }
  
  // Update delete button SVG color
  const deleteButton = bannerElement.querySelector('button');
  if (deleteButton) {
    deleteButton.innerHTML = `
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M18 6L6 18" stroke="${textColor}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
        <path d="M6 6L18 18" stroke="${textColor}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
      </svg>
    `;
  }
}

// Check if the current URL matches any of the configured URL settings
function checkAndAddBanner(urlSettings, bannerPosition = 'top-center') {
  const currentUrl = window.location.href;
  
  for (const setting of urlSettings) {
    if (currentUrl.match(new RegExp(setting.url))) {
      addWarningBanner(setting.warningText, setting.backgroundColor, setting.textColor, bannerPosition);
      break; // Only show one banner, even if multiple settings match
    }
  }
}

// Load settings from storage
chrome.storage.sync.get(['urlSettings', 'bannerPosition'], function(items) {
  const urlSettings = items.urlSettings || [];
  const bannerPosition = items.bannerPosition || 'top-center';
  
  if (urlSettings.length > 0) {
    checkAndAddBanner(urlSettings, bannerPosition);
  }
  
  // Listen for URL changes (for single page applications)
  let lastUrl = location.href;
  new MutationObserver(() => {
    const url = location.href;
    if (url !== lastUrl) {
      lastUrl = url;
      // Add a small delay to ensure URL has fully changed
      setTimeout(() => {
        if (urlSettings.length > 0) {
          checkAndAddBanner(urlSettings, bannerPosition);
        }
      }, 100);
    }
  }).observe(document, { subtree: true, childList: true });
});